<?php

namespace app\api\controller;

use app\common\controller\Api;
use think\Db;
use think\Exception;
use think\exception\PDOException;
use think\exception\ValidateException;
use think\Request;

/**
 * 积分专区
 */
class NewOrder extends Api
{
    protected $noNeedLogin = ['*'];
    protected $noNeedRight = ['*'];

    //立即购买生成订单
    public function create_order()
    {
        $request = Request::instance();
        $userId = $request->param("userhome_id");
        $data = [
            'goods_spec_one_id' => $request->param("goods_spec_one_id"),//商品属性id
            'goods_spec_two_id' => $request->param("goods_spec_two_id"),//商品属性id
            'num' => $request->param("num"),//商品数量
            'address_id' => $request->param("address_id"),//地址id
            'paytype' => $request->param("paytype"),//地址id
        ];
        $res = yanzheng($userId, $this->request->param("token"), $this->request->param("jm_str"));
        if ($res == 0) {
            $this->error('账号异常', '', 206);
        }
        if ($res == 1) {
            $this->error('非法的请求', '', 201);
        }
        $EmptyData = array('goods_spec_one_id', 'goods_spec_two_id', 'num', 'address_id', 'paytype');
        foreach ($EmptyData as $oeVo) {
            $retInfo = EmptyValidate($oeVo, $data);
            if ($retInfo) {
                $this->error($retInfo, '', 201);
            }
        }
        $car = [];
        $car['userhome_id'] = $userId;
        $car['goods_spec_one_id'] = $data['goods_spec_one_id'];
        $car['goods_spec_two_id'] = $data['goods_spec_two_id'];
        $car['num'] = $data['num'];
        $data['buy_car_id'] = DB::name('buy_car')->insertGetId($car);
        $res = $this->getCarGoods($data, $userId);
        DB::name('buy_car')->where('id', 'in', $data['buy_car_id'])->delete();
        //返回支付单号
        $this->success('OK', $res, 200);
    }

    //运费计算
    public function getFreight()
    {
        //return var_dump(kuaidi_usable());
        $request = Request::instance();
        $address_id = $request->param("address_id");
        $goods_id = $request->param("goods_id");
        $num = $request->param("num");
        $goods = DB::name('goods')->where('id', $goods_id)->find();
        $expressfee_id = $goods['expressfee_id'];
        $zhongliang = $goods['zhongliang'];
        $good_name = $goods['name'];
        $address = DB::name('useraddress')->where('id', $address_id)->find();
        //$wuliu = kuaidi();
        $freight = $this->getFreightRule($address, $expressfee_id, $zhongliang, $num, $good_name);
        $this->success('OK', ['freight' => $freight], 200);
    }

    //运费计算
    public function getCarFreight()
    {
        $request = Request::instance();
        $data = [
            'buy_car_id' => $request->param("buy_car_id"),//商品数量
            'address_id' => $request->param("address_id")//地址id
        ];
        $EmptyData = array('buy_car_id', 'address_id');
        foreach ($EmptyData as $oeVo) {
            $retInfo = EmptyValidate($oeVo, $data);
            if ($retInfo) {
                $this->error($retInfo, '', 201);
            }
        }
        $userId = $request->param("userhome_id");//用户id
        $res = yanzheng($userId, $this->request->param("token"), $this->request->param("jm_str"));
        if ($res == 0) {
            $this->error('账号异常', '', 206);
        }
        if ($res == 1) {
            $this->error('非法的请求', '', 201);
        }
        $good = DB::name('buy_car t0')
            ->join('goods_spec_one t2', 't0.goods_spec_one_id = t2.id')
            ->join('goods_spec_two t3', 't0.goods_spec_two_id = t3.id', "LEFT")
            ->join('goods_stock t4', 't0.goods_spec_one_id = t4.goods_spec_one_id and t0.goods_spec_two_id = t4.goods_spec_two_id')
            ->join('goods t1', 't4.goods_id = t1.id')
            ->whereIn('t0.id', explode(',',$data['buy_car_id']))
            ->where('t0.userhome_id', $userId)
            ->field("t1.id as goods_id,t1.supplier_id,t1.brand_id,t1.shuilv,t1.name as goods_name,t1.expressfee_id,t1.zhongliang,t1.integral,
                t4.goods_spec_one_id,t4.goods_spec_two_id,t4.cost_price,t4.price,t4.use_integral,t4.image as goods_image,t1.return_mode_id,t2.name as goods_spec_one_name,t3.name as goods_spec_two_name,t0.num,t1.expressfee_id,t1.zhongliang")
            ->select();
        //return var_dump($good);
        $freight = 0;
        $address = DB::name('useraddress')->where('id', $data['address_id'])->find();
        foreach ($good as $key => $value) {
            $freight = $freight + $this->getFreightRule($address, $value['expressfee_id'], $value['zhongliang'], $value['num'], $value['goods_name']);
        }
        $this->success('OK', ['freight' => $freight], 200);
    }

    public function getFreightRule($address, $expressfee_id, $zhongliang, $num, $good_name)
    {
        //地址-运费id-重量-数量-商品名称
        $freight = 0;
        if ($address) {
            $expressfee = DB::name('expressfee')->where('id', $expressfee_id)->find();
            if ($expressfee) {
                $region = DB::name('district t1')
                    ->join('expressfeecity_c t2', 't1.district_id = t2.area_id')
                    ->where('t1.district_id', $address['pro_id'])
                    ->where('t2.expressfeeid', $expressfee_id)
                    ->field('t2.*')
                    ->find();
                if (!empty($region)) {
                    //若不为空。则进入运费计算
                    $freight = $this->calculateFreight($region, $zhongliang, $num);
                } else {
                    $this->error($good_name . '该地区不支持发货', '', 397);
                }
//                if ($expressfee['type'] == 0) {
//                    $expressfeecity_b = DB::name('expressfeecity_b')->where('expressfeeid', $expressfee_id)->where('area_id', $address['pro_id'])->find();
//                    if ($expressfeecity_b) {
//                        $region = DB::name('district t1')
//                            ->join('district t2', 't1.pid = t2.district_id')
//                            ->join('expressfeecity_b t3', 't2.district_id = t3.area_id')
//                            ->where('t1.district_id', $address['pro_id'])
//                            ->where('t3.expressfeeid', $expressfee_id)
//                            ->field('t3.*')
//                            ->find();
//                        if (!empty($region) && !empty($region['freightList'])) {
//                            $freight = $this->calculateFreight($region, $zhongliang, $num);
//                        }
//                    }
//                } else {
//                    $expressfeecity_b = DB::name('expressfeecity_b')->where('expressfeeid', $expressfee_id)->where('area_id', $address['pro_id'])->find();
//                    if ($expressfeecity_b) {
//                        $region = DB::name('district t1')
//                            ->join('district t2', 't1.pid = t2.district_id')
//                            ->join('expressfeecity_b t3', 't2.district_id = t3.area_id')
//                            ->where('t1.district_id', $address['pro_id'])
//                            ->where('t3.expressfeeid', $expressfee_id)
//                            ->field('t3.*')
//                            ->find();
//                        if (!empty($region) && !empty($region['freightList'])) {
//                            $freight = $this->calculateFreight($region, $zhongliang, $num);
//                        } else {
//                            $this->error($good_name . '在该地区不支持发货', '', 397);
//                        }
//                    } else {
//                        $this->error($good_name . '该地区不支持发货', '', 397);
//                    }
                //}
            } else {
                $this->error($good_name . '未查询到运费信息', '', 398);
            }
        } else {
            $this->error('未查询到地址信息', '', 399);
        }
        return $freight;
    }

    public function calculateFreight($region, $zhongliang, $num)
    {
        $freight = 0;
        $yc_expressfeecity_b = DB::name('expressfeecity_b')->where('id', $region['expressfeecity_b_id'])->field("*")->find();
        if ($yc_expressfeecity_b) {
            $type = $yc_expressfeecity_b['type'];
            $unit = $yc_expressfeecity_b['unit'];
            $freightList = $yc_expressfeecity_b['freightList'];
            $rule = $num;
            if ($unit == 0) {
                $rule = $zhongliang * $num;
            }
            $freightList = json_decode($freightList);
            if (isset($freightList->fweight[0]) && isset($freightList->tweight[0])) {
                if ($type == 0) {
                    $num = count($freightList->fweight) - 1;
                    if ($rule > $freightList->fweight[$num - 1]) {
                        $freight = ($freightList->tweight[$num] * intval(($rule - $freightList->fweight[$num - 1]) / $freightList->fweight[$num])) + $freightList->tweight[$num - 1];
                    } else {
                        foreach ($freightList->fweight as $key => $value) {
                            if ($rule <= $value) {
                                $freight = $freightList->tweight[$key];
                                break;
                            }
                        }
                    }
                } else {
                    if ($rule > $freightList->fweight[0]) {
                        if (isset($freightList->fweight[1]) && isset($freightList->tweight[1])) {
                            $freight = ($freightList->tweight[1] * intval(($rule - $freightList->fweight[0]) / $freightList->fweight[1])) + $freightList->tweight[0];
                        } else {
                            $freight = $freightList->tweight[0];
                        }
                    } else {
                        $freight = $freightList->tweight[0];
                    }
                }
            } else {
                $freight = 0;
            }
        } else {
            $freight = 0;
        }
        return $freight;
    }

    public function car_create_order()
    {
        $request = Request::instance();
        $data = [
            'buy_car_id' => $request->param("buy_car_id"),//商品数量
            'address_id' => $request->param("address_id"),//地址id
            'paytype' => $request->param("paytype"),//地址id
        ];
        $EmptyData = array('buy_car_id', 'address_id', 'paytype');
        foreach ($EmptyData as $oeVo) {
            $retInfo = EmptyValidate($oeVo, $data);
            if ($retInfo) {
                $this->error($retInfo, '', 201);
            }
        }
        $userId = $request->param("userhome_id");//用户id
        $res = yanzheng($userId, $this->request->param("token"), $this->request->param("jm_str"));
        if ($res == 0) {
            $this->error('账号异常', '', 206);
        }
        if ($res == 1) {
            $this->error('非法的请求', '', 201);
        }
        $res = $this->getCarGoods($data, $userId);
        //返回支付单号
        $this->success('OK', $res, 200);
    }

    public
    function getCarGoods($data, $userId, $isActivity = 0)
    {
        $good = DB::name('buy_car t0')
            ->join('goods_spec_one t2', 't0.goods_spec_one_id = t2.id')
            ->join('goods_spec_two t3', 't0.goods_spec_two_id = t3.id', "LEFT")
            ->join('goods_stock t4', 't0.goods_spec_one_id = t4.goods_spec_one_id and t0.goods_spec_two_id = t4.goods_spec_two_id')
            ->join('goods t1', 't4.goods_id = t1.id')
            ->where('t0.id', 'in', $data['buy_car_id'])
            ->where('t0.userhome_id', $userId)
            ->field("t1.status,t1.is_del,t4.vip_price,t1.id as goods_id,t1.supplier_id,t1.brand_id,t1.shuilv,t1.name as goods_name,t1.expressfee_id,t1.zhongliang,t1.integral,t1.createtime,
                t4.goods_spec_one_id,t4.goods_spec_two_id,t4.cost_price,t4.pure_cost_price,t4.price,t4.use_integral,t4.image as goods_image,t1.return_mode_id,t2.name as goods_spec_one_name,t3.name as goods_spec_two_name,t0.num,t1.expressfee_id,t1.zhongliang")
            ->select();
        $cutOffTime = strtotime("2022-11-02 23:59:59");
        $goodsList = [];
        foreach ($good as $key => $value) {
            if($value['createtime'] <= $cutOffTime){
                $this->error('因疫情原因,当地区已不支持发货', '', 391);
            }
            if($value['num'] <= 0){
                $this->error($value['goods_name'] . "商品请重新添加购物车");
            }
            if ($isActivity) {
                if (($value['status'] == 2) || ($value['status'] == 1) || $value['is_del'] != 0) {
                    $this->error($value['goods_name'] . "已被下架");
                }
            } else {
                if (($value['status'] != 1) || $value['is_del'] != 0) {
                    $this->error($value['goods_name'] . "已被下架");
                }
            }
            $goodsList[$value['goods_id']][] = $value;
        }
        $address = DB::name('useraddress')->where(['userhome_id' => $userId, 'id' => $data['address_id']])->find();
        if(!$address){
            $this->error("地址已消失");
        }
        $address['address'] = $address['pro_name'] . $address['city_name'] . $address['area_name'] . $address['address'];
        $res = $this->setTheOrder($goodsList, $userId, $data['paytype'], $address, $isActivity);
        DB::name('buy_car')->where('id', 'in', $data['buy_car_id'])->delete();
        return $res;
    }

    private function setTheOrder($goodsList, $userId, $paytype, $address, $isActivity)
    {
        $user = Db::name("userhome")->where(['id' => $userId])->find();
        $isVip = $user['isVip'];
        $orderIsVip = $isVip;
        $activityStatus = 0;
        if ($isActivity == 30) {
            $activityStatus = $isActivity;
            $orderIsVip = 0;
            $isVip = 1;
        }else if ($isActivity == 40) {
            $activityStatus = $isActivity;
            $orderIsVip = 0;
            $isVip = 0;
        }else{
            if($orderIsVip){
                $activityStatus = 10;
            }
        }
        $paycode = date('Ymd') . '1' . substr(implode(NULL, array_map('ord', str_split(substr(uniqid(), 7, 13), 1))), 0, 8) . rand(0, 9);//生成支付单号
        $order_id = 0;
        try {
            Db::startTrans();
            $i = -1;
            $time = time();
            foreach ($goodsList as $value) {
                $i++;
                $orderDetail = [];
                $totalExpressFee = 0;
                $totalGoodsPrice = 0;
                $totalGoodsVipPrice = 0;
                $allPrice = 0;
                $addIntegral = 0;
                $supplier_cost = 0;
                $supplier_id = null;
                foreach ($value as $key => $val) {
                    $supplier_id = $val['supplier_id'];
                    $expressFee = 0;
                    //子单运费
                    $expressFee = $this->getFreightRule($address, $val['expressfee_id'], $val['zhongliang'], $val['num'], $val['goods_name']);
                    //子单实际支付
                    if ($isVip) {
                        $realityPrice = $val['vip_price'] * $val['num'];
                    } else {
                        $realityPrice = $val['price'] * $val['num'];
                    }
                    $orderDetail[$key]['return_mode_id'] = $val['return_mode_id'];
                    $orderDetail[$key]['userhome_id'] = $userId;
                    $orderDetail[$key]['goods_id'] = $val['goods_id'];
                    $orderDetail[$key]['goods_spec_one_id'] = $val['goods_spec_one_id'];
                    $orderDetail[$key]['goods_spec_two_id'] = $val['goods_spec_two_id'];
                    $orderDetail[$key]['image'] = $val['goods_image'];
                    $orderDetail[$key]['name'] = $val['goods_name'];
                    if (isset($val['goods_spec_two_name'])) {
                        $orderDetail[$key]['goods_spec_name'] = $val['goods_spec_one_name'] . "/" . $val['goods_spec_two_name'];
                    } else {
                        $orderDetail[$key]['goods_spec_name'] = $val['goods_spec_one_name'];
                    }
                    $orderDetail[$key]['num'] = $val['num'];
                    $orderDetail[$key]['shuilv'] = $val['shuilv'];
                    $orderDetail[$key]['cost_price'] = $val['cost_price'];
                    $orderDetail[$key]['pure_cost_price'] = $val['pure_cost_price'];
                    $orderDetail[$key]['price'] = $val['price'];
                    $orderDetail[$key]['vip_price'] = $val['vip_price'];
                    $orderDetail[$key]['integral'] = $val['use_integral'];
                    $orderDetail[$key]['realityFreight'] = $expressFee;
                    $orderDetail[$key]['realityPrice'] = $realityPrice;
                    $orderDetail[$key]['activityStatus'] = $activityStatus;
                    //计算大订单全部运费
                    $totalExpressFee = $totalExpressFee + $expressFee;
                    //计算大订单全部商品成本
                    $totalGoodsPrice = $totalGoodsPrice + ($val['price'] * $val['num']);
                    //计算vip金额
                    $totalGoodsVipPrice = $totalGoodsVipPrice + ($val['vip_price'] * $val['num']);
                    //计算大订单全部实际付款
                    $allPrice = $allPrice + $realityPrice + $expressFee;
                    $addIntegral = $addIntegral + $val['use_integral'];
                    $supplier_cost = $supplier_cost + ($val['cost_price'] * $val['num']);
                }
                unset($key);
                unset($val);
                $order = [
                    'supplier_id' => $supplier_id,
                    'userhome_id' => $userId,
                    'ordernum' => date('Ymd') . '2' . substr(implode(NULL, array_map('ord', str_split(substr(uniqid(), 6, 12), 1))), 0, 8) . rand(0, 9),//生成订单号
                    'paycode' => $paycode,
                    'orderpaytype' => 1,
                    'paytype' => $paytype,
                    'price' => $totalGoodsPrice,
                    'vip_price' => $totalGoodsVipPrice,
                    'freight' => $totalExpressFee,
                    'allprice' => $allPrice,
                    'phone' => $address['phone'],
                    'name' => $address['name'],
                    'address' => $address['address'],
                    'createtime' => $time,
                    'use_integral' => $addIntegral,
                    'supplier_cost' => $supplier_cost,
                    'isVip' => $orderIsVip,
                    'versions' => 1,
                    'activityStatus' => $activityStatus
                ];
                $order_id = DB::name('order')->insertGetId($order);
                foreach ($orderDetail as $key => $val) {
                    $orderDetail[$key]['order_id'] = $order_id;
                }
                //订单详情
                DB::name('orderdetail')->insertAll($orderDetail);
                unset($key);
                unset($val);
            }
            Db::commit();
        } catch (ValidateException $e) {
            Db::rollback();
            $this->error($e->getMessage());
        } catch (PDOException $e) {
            Db::rollback();
            $this->error($e->getMessage());
        } catch (Exception $e) {
            Db::rollback();
            $this->error($e->getMessage());
        }
        $data = [];
        $data['paycode'] = $paycode;
        $data['order_id'] = $order_id;
        return $data;
    }

//app的微信支付-会员
    public
    function app_vip_wx()
    {
        $request = Request::instance();
        $userId = $request->param("uid");
        $vipId = $request->param("vipId");
        $vip = Db::name("vip")->where('vipId', $vipId)->find();
        if (!isset($vip)) {
            $this->error('请选择充值类型', '', 209);
        }
        $res = yanzheng($userId, $this->request->param("token"), $this->request->param("jm_str"));
        if ($res == 0) {
            $this->error('账号异常', '', 206);
        }
        if ($res == 1) {
            $this->error('非法的请求', '', 201);
        }
        $orderNum = time() . "U$userId" . "V$vipId";
        $total_fee = $vip['vipPrice'] * 100;
        if ($total_fee <= 0) {
            $this->error('金额不能是0', '', 201);
        }

        //...
        include './WeixinPay.php';
        $wx = new \WeixinPay();//实例化微信支付控制器
        $root_http = getSystem("root_http");
        $http = $root_http . $_SERVER['SERVER_NAME'];
        $body = "vip充值";
        // $total_fee = 1;//支付金额(乘以100)
        $notify_url = $http . "/api/new_order/wx_callback_api_vip";
        $order = $wx->getPrePayOrder($body, $orderNum, $total_fee, $notify_url);
        //dump($order);die;
        if (isset($order['prepay_id'])) {//判断返回参数中是否有prepay_id
            $order1 = $wx->getOrder($order['prepay_id']);//执行二次签名返回参数
            //dump($order1);die;
            $this->success('成功', $order1, 200);
        } else {
            $this->error('失败', $order['return_msg'], 201);
        }
    }

//app的支付宝支付-会员
    public
    function app_vip_zfb()
    {
        $request = Request::instance();
        $userId = $request->param("uid");
        $vipId = $request->param("vipId");
        $vip = Db::name("vip")->where('vipId', $vipId)->find();
        if (!isset($vip)) {
            $this->error('请选择充值类型', '', 209);
        }
        $res = yanzheng($userId, $this->request->param("token"), $this->request->param("jm_str"));
        if ($res == 0) {
            $this->error('账号异常', '', 206);
        }
        if ($res == 1) {
            $this->error('非法的请求', '', 201);
        }
        $orderNum = time() . "U$userId" . "V$vipId";
        $total_fee = $vip['vipPrice'];
        if ($total_fee <= 0) {
            $this->error('金额不能是0', '', 201);
        }

        //支付宝
        include "./aop/AopClient.php";
        include "./aop/AopCertClient.php";
        include "./aop/request/AlipayTradeAppPayRequest.php";
        $c = new \AopCertClient;
        $root_path = getSystem("root_path");
        $appCertPath = $root_path . "public/zhengshu/appCertPublicKey_2021002182617884.crt";//应用公钥
        $alipayCertPath = $root_path . "public/zhengshu/alipayCertPublicKey_RSA2.crt";//支付宝公钥
        $rootCertPath = $root_path . "public/zhengshu/alipayRootCert.crt";//支付宝根证书
        $c->gatewayUrl = "https://openapi.alipay.com/gateway.do";
        $c->appId = "2021002182617884";
        $c->rsaPrivateKey = 'MIIEvgIBADANBgkqhkiG9w0BAQEFAASCBKgwggSkAgEAAoIBAQCykKr+nuwgwviNEAEdUD7BomIPSFn25XM7a2dzaBLLwVZbC1AZ6PsCGjDyIeTi/L8WECZ/m251cc05ntBfIlnIawwX8DsnZB7/O8usL21rjVyatUFTzW+gz0v7/H0OAj/503g8jBczWFbnxONmstaAo7VCLQ163qfkEYB3a3uo/jMbm0TmvJ50QKh75uvazlptXBxmqUlEhj1qicpdyhz99cbS/2bn4Ci+5CcY9UIBIlXn/iGCWQ/CvxpXbtKGKUQu9UmdROCcM5D5SmEiSWTBn5Pt5tJzTWqK3h+wxlaArdAvf/YOJUin7GoXgjSguRJ28NXftsmt0vT9Johe+cAxAgMBAAECggEATHpjkjw0u+9ljt0s7QYiasKGpy8AwRsS2H8uxqHrcvMybjoRK5e6cfMPxZS4uHMx0FxIcNz8WTbNhAE+E5DdzVXzzwjn/P4HvJ86o1uIzMi1wdkhyqexSLmgPKOuV+KkzfZBiAUkJqyORCPylVjBQEVda6NqI5bbZ3YLhJo3U3Ab4uBwT8YG8SzETFGHbG8Vqvb4rkFuMUSWm2aczD2JVRYuPoTmjsSezp9x9s6f+wsIqZC/5PmEMG0xfH9fUEXs+OHBVVu58JCJMwo4EwewBN8fWQTGLPJIZiUsLqtWCUHJ7/wSNU/Mp8RtDzaXKFfiuw8Mrc4J2dldUOOlXqS6AQKBgQDu7LaupzOsD3VizUIsxRoG/iIIIktARJJgoRxo+HU0vJ31tQbMntgqR5/VMp4tXa5tCSUZYgYSL7C1bqfHXouHDGj4/OZ+2cGqpYnGGfgNmlgoVi5hb4ncG72ggOYkDwsgv8mCFlyTvDykTb1M5z+upm2uxrIdVK55RRf88V2RIQKBgQC/U6LPGksYUtRcZCQGEa18FWT3aHlRun5m9fEdCjdMGXkhbxPMiFDg/JFtaeVzo7CUxBgMpLPpTOO/gT6FtWPsJvusP67W03yQR7ysdZKtrGPBXARwmQPHahGsV+2BoXk2kObVuc1EaA0oZFOLaJp1sOKEkJIf1zPU1PgBfSZ9EQKBgQCr0buGWmPEhtFqHiZKv+v5v2SF6POo4idKKlKeAp93L3WBL5AWMt1Nenis/1vVUBuR+hOd72piRb2UnGE39PvuQLR06ppv+vVVXPp5Zk+GqMphJ6jvFSFVEvYJqOjYYaElCgdF8ALfk20g028hEOQxGyqhl+6bPTzDpTadBo69QQKBgQCSssQg2948djYR6U6dwKwuehECin6LJd2JgIYxaAXiOZ3g/tRFfTfWapHvPMUMF7RrPLfb6eVwut3dlnGj/+LvzSwndGTQnzPhRL/r0/J1a7rJJY7Z7tkw66lFZd3cCT1xk0ULFv3Gt6lvEQ3l1HyqRMhKMLd55n39cJYAPj9moQKBgBuuK0vSf+9BhqK8/msXlPAYEHv/LFFH1ufvYKu6uPZuGWYWJsrFc+l/xhr1tmebPnENhSb5cZHRdwnq09K0HAGKV1NvNmQdrnvFAOANdb22Ovu8Q4Bbp1NVp28IjaDOR6CAXOcCM1HUJVMuqHHQ3123ISp10W2JNE67ss49lnB0';
        $c->format = "json";
        $c->charset = "GBK";
        $c->signType = "RSA2";
        //调用getPublicKey从支付宝公钥证书中提取公钥
        $c->alipayrsaPublicKey = $c->getPublicKey($alipayCertPath);
        //是否校验自动下载的支付宝公钥证书，如果开启校验要保证支付宝根证书在有效期内
        $c->isCheckAlipayPublicCert = true;
        //调用getCertSN获取证书序列号
        $c->appCertSN = $c->getCertSN($appCertPath);
        //调用getRootCertSN获取支付宝根证书序列号
        $c->alipayRootCertSN = $c->getRootCertSN($rootCertPath);
        $request2 = new \AlipayTradeAppPayRequest();
        //SDK已经封装掉了公共参数，这里只需要传入业务参数
        $remark = 'vip充值';
        // $yue_sn = time();//这里是单号
        // $money = '0.01';
        $bizcontent = "{\"body\":\"云仓小店\","
            . "\"subject\": \"{$remark}\","
            . "\"out_trade_no\": \"{$orderNum}\","
            . "\"timeout_express\": \"30m\","
            . "\"total_amount\": \"{$total_fee}\","
            . "\"product_code\":\"QUICK_MSECURITY_PAY\""
            . "}";
        // $notify_url = "https://".$_SERVER['SERVER_NAME']."/api/index/zfb_callback";

        $notify_url = "https://" . $_SERVER['SERVER_NAME'] . "/api/new_order/zfb_callback_api_vip";
        // echo $notify_url;die;

        $request2->setNotifyUrl($notify_url);
        $request2->setBizContent($bizcontent);
        $response = $c->sdkExecute($request2);
        $this->success('成功', $response, 200);
    }

//小程序的微信支付-会员
    public
    function xcx_vip()
    {
        $request = Request::instance();
        $userId = $request->param("uid");
        $vipId = $request->param("vipId");
        $vip = Db::name("vip")->where('vipId', $vipId)->find();
        $openid = $request->param("openid");//
        if (!isset($vip)) {
            $this->error('请选择充值类型', '', 209);
        }
        $res = yanzheng($userId, $this->request->param("token"), $this->request->param("jm_str"));
        if ($res == 0) {
            $this->error('账号异常', '', 206);
        }
        if ($res == 1) {
            $this->error('非法的请求', '', 201);
        }
        $orderNum = time() . "U$userId" . "V$vipId";
        $total_fee = $vip['vipPrice'] * 100;
        if ($total_fee <= 0) {
            $this->error('金额不能是0', '', 201);
        }

        //...
        require_once "./WeixinPayXcx.php";
        $body = "vip充值";
        // $total_fee = 1;
        $root_http = getSystem("root_http");
        $http = $root_http . $_SERVER['SERVER_NAME'];
        $notify_url = $http . "/api/new_order/wx_callback_api_vip";
        //return var_dump($notify_url);
        if (!isset($openid) || empty($openid)) {
            $xcxopenid = DB::name('userhome')->where('id', $userId)->value('appletOpenid');
            if (empty($xcxopenid)) {
                $xcxopenid = DB::name('userhome')->where('id', $userId)->value('xcxopenid');
            }
        } else {
            $xcxopenid = $openid;
        }
        // $xcxopenid = 'oj6aC5ZRZ1B4Gaej0DbGI0cG5640';
        $weixinpay = new \WeixinPayXcx('wx4a40935421da4a92', $xcxopenid, '1615039358', '7f63d80284392beae6974f43c5c40a59', $orderNum, $body, $total_fee, $notify_url);
        $return = $weixinpay->pay();
        $this->success('ok', $return, 200);
    }

//pc的微信支付-会员
    public
    function pc_vip_wx()
    {
        $request = Request::instance();
        $userId = $request->param("uid");
        $vipId = $request->param("vipId");
        $vip = Db::name("vip")->where('vipId', $vipId)->find();
        $openid = $request->param("openid");//
        if (!isset($vip)) {
            $this->error('请选择充值类型', '', 209);
        }
        $res = yanzheng($userId, $this->request->param("token"), $this->request->param("jm_str"));
        if ($res == 0) {
            $this->error('账号异常', '', 206);
        }
        if ($res == 1) {
            $this->error('非法的请求', '', 201);
        }
        $orderNum = time() . "U$userId" . "V$vipId";
        $total_fee = $vip['vipPrice'] * 100;
        if ($total_fee <= 0) {
            $this->error('金额不能是0', '', 201);
        }

        //...
        include './WeixinPay.php';
        $wx = new \WeixinPay();//实例化微信支付控制器
        $root_http = getSystem("root_http");
        $http = $root_http . $_SERVER['SERVER_NAME'];
        $body = "vip充值";
        // $total_fee = 1;//支付金额(乘以100)
        $notify_url = $http . "/api/new_order/wx_callback_api_vip";
        $order = $wx->getPrePcPayOrder($body, $orderNum, $total_fee, $notify_url);
        //dump($order);die;
        if (isset($order['code_url'])) {//判断返回参数中是否有prepay_id
            //$order1 = $wx->getOrder($order['prepay_id']);//执行二次签名返回参数
            //dump($order1);die;
            $this->success('成功', $order['code_url'], 200);
        } else {
            $this->error('失败', $order['return_msg'], 201);
        }
    }

//pc的支付宝支付-会员
    public
    function pc_vip_zfb()
    {
        $request = Request::instance();
        $userId = $request->param("uid");
        $vipId = $request->param("vipId");
        $vip = Db::name("vip")->where('vipId', $vipId)->find();
        if (!isset($vip)) {
            $this->error('请选择充值类型', '', 209);
        }
        $res = yanzheng($userId, $this->request->param("token"), $this->request->param("jm_str"));
        if ($res == 0) {
            $this->error('账号异常', '', 206);
        }
        if ($res == 1) {
            $this->error('非法的请求', '', 201);
        }
        $orderNum = time() . "U$userId" . "V$vipId";
        $total_fee = $vip['vipPrice'];
        if ($total_fee <= 0) {
            $this->error('金额不能是0', '', 201);
        }
        $remark = 'vip充值';
        //支付宝
        include "./aop/AopClient.php";
        include "./aop/AopCertClient.php";
        include "./aop/request/AlipayTradePagePayRequest.php";
        $notify_url = "https://" . $_SERVER['SERVER_NAME'] . "/api/new_order/zfb_callback_api_vip";
        $root_path = getSystem("root_path");
        $appCertPath = $root_path . "public/zhengshu/appCertPublicKey_2021002182617884.crt";//应用公钥
        $alipayCertPath = $root_path . "public/zhengshu/alipayCertPublicKey_RSA2.crt";//支付宝公钥
        $rootCertPath = $root_path . "public/zhengshu/alipayRootCert.crt";//支付宝根证书
        $aop = new \AopCertClient;
        $aop->gatewayUrl = 'https://openapi.alipay.com/gateway.do';
        $aop->appId = '2021002182617884';
        $aop->rsaPrivateKey = 'MIIEvgIBADANBgkqhkiG9w0BAQEFAASCBKgwggSkAgEAAoIBAQCykKr+nuwgwviNEAEdUD7BomIPSFn25XM7a2dzaBLLwVZbC1AZ6PsCGjDyIeTi/L8WECZ/m251cc05ntBfIlnIawwX8DsnZB7/O8usL21rjVyatUFTzW+gz0v7/H0OAj/503g8jBczWFbnxONmstaAo7VCLQ163qfkEYB3a3uo/jMbm0TmvJ50QKh75uvazlptXBxmqUlEhj1qicpdyhz99cbS/2bn4Ci+5CcY9UIBIlXn/iGCWQ/CvxpXbtKGKUQu9UmdROCcM5D5SmEiSWTBn5Pt5tJzTWqK3h+wxlaArdAvf/YOJUin7GoXgjSguRJ28NXftsmt0vT9Johe+cAxAgMBAAECggEATHpjkjw0u+9ljt0s7QYiasKGpy8AwRsS2H8uxqHrcvMybjoRK5e6cfMPxZS4uHMx0FxIcNz8WTbNhAE+E5DdzVXzzwjn/P4HvJ86o1uIzMi1wdkhyqexSLmgPKOuV+KkzfZBiAUkJqyORCPylVjBQEVda6NqI5bbZ3YLhJo3U3Ab4uBwT8YG8SzETFGHbG8Vqvb4rkFuMUSWm2aczD2JVRYuPoTmjsSezp9x9s6f+wsIqZC/5PmEMG0xfH9fUEXs+OHBVVu58JCJMwo4EwewBN8fWQTGLPJIZiUsLqtWCUHJ7/wSNU/Mp8RtDzaXKFfiuw8Mrc4J2dldUOOlXqS6AQKBgQDu7LaupzOsD3VizUIsxRoG/iIIIktARJJgoRxo+HU0vJ31tQbMntgqR5/VMp4tXa5tCSUZYgYSL7C1bqfHXouHDGj4/OZ+2cGqpYnGGfgNmlgoVi5hb4ncG72ggOYkDwsgv8mCFlyTvDykTb1M5z+upm2uxrIdVK55RRf88V2RIQKBgQC/U6LPGksYUtRcZCQGEa18FWT3aHlRun5m9fEdCjdMGXkhbxPMiFDg/JFtaeVzo7CUxBgMpLPpTOO/gT6FtWPsJvusP67W03yQR7ysdZKtrGPBXARwmQPHahGsV+2BoXk2kObVuc1EaA0oZFOLaJp1sOKEkJIf1zPU1PgBfSZ9EQKBgQCr0buGWmPEhtFqHiZKv+v5v2SF6POo4idKKlKeAp93L3WBL5AWMt1Nenis/1vVUBuR+hOd72piRb2UnGE39PvuQLR06ppv+vVVXPp5Zk+GqMphJ6jvFSFVEvYJqOjYYaElCgdF8ALfk20g028hEOQxGyqhl+6bPTzDpTadBo69QQKBgQCSssQg2948djYR6U6dwKwuehECin6LJd2JgIYxaAXiOZ3g/tRFfTfWapHvPMUMF7RrPLfb6eVwut3dlnGj/+LvzSwndGTQnzPhRL/r0/J1a7rJJY7Z7tkw66lFZd3cCT1xk0ULFv3Gt6lvEQ3l1HyqRMhKMLd55n39cJYAPj9moQKBgBuuK0vSf+9BhqK8/msXlPAYEHv/LFFH1ufvYKu6uPZuGWYWJsrFc+l/xhr1tmebPnENhSb5cZHRdwnq09K0HAGKV1NvNmQdrnvFAOANdb22Ovu8Q4Bbp1NVp28IjaDOR6CAXOcCM1HUJVMuqHHQ3123ISp10W2JNE67ss49lnB0';
        //$aop->alipayrsaPublicKey = 'MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAspCq/p7sIML4jRABHVA+waJiD0hZ9uVzO2tnc2gSy8FWWwtQGej7Ahow8iHk4vy/FhAmf5tudXHNOZ7QXyJZyGsMF/A7J2Qe/zvLrC9ta41cmrVBU81voM9L+/x9DgI/+dN4PIwXM1hW58TjZrLWgKO1Qi0Net6n5BGAd2t7qP4zG5tE5ryedECoe+br2s5abVwcZqlJRIY9aonKXcoc/fXG0v9m5+AovuQnGPVCASJV5/4hglkPwr8aV27ShilELvVJnUTgnDOQ+UphIklkwZ+T7ebSc01qit4fsMZWgK3QL3/2DiVIp+xqF4I0oLkSdvDV37bJrdL0/SaIXvnAMQIDAQAB';
        //调用getPublicKey从支付宝公钥证书中提取公钥
        $aop->alipayrsaPublicKey = $aop->getPublicKey($alipayCertPath);
        //是否校验自动下载的支付宝公钥证书，如果开启校验要保证支付宝根证书在有效期内
        $aop->isCheckAlipayPublicCert = true;
        //调用getCertSN获取证书序列号
        $aop->appCertSN = $aop->getCertSN($appCertPath);
        //调用getRootCertSN获取支付宝根证书序列号
        $aop->alipayRootCertSN = $aop->getRootCertSN($rootCertPath);
        $aop->apiVersion = '1.0';
        $aop->signType = 'RSA2';
        $aop->postCharset = 'UTF-8';
        $aop->format = 'json';
        $object = new \stdClass();
        $object->out_trade_no = $orderNum;
        $object->total_amount = $total_fee;
        $object->subject = $remark;
        $object->product_code = 'FAST_INSTANT_TRADE_PAY';
        $object->time_expire = date("Y-m-d H:i:s", strtotime("+30 minute"));
        //return var_dump($object->time_expire);
        //$object->qr_pay_mode = '2';
        $json = json_encode($object);
        $request = new \AlipayTradePagePayRequest();
        $request->setNotifyUrl($notify_url);
        $request->setBizContent($json);
        $result = $aop->pageExecute($request, "get");
        $this->success('成功', $result, 200);
    }

    private
    function setVip($orderNum, $payType, $payCode)
    {
        $oldOrderNum = $orderNum;
        $orderNum = explode("U", $orderNum);
        $orderNum = $orderNum[1];
        $orderNum = explode("V", $orderNum);
        $userId = $orderNum[0];
        $vipId = $orderNum[1];
        try {
            Db::startTrans();
            $user = Db::name("userhome")->where(['id' => $userId])->lock(true)->find();
            if (!$user['isVip']) {
                $userStatistics = Db::name("user_statistics")->where('createDay', date("Y-m-d"))->where('type', 3)->find();
                if ($userStatistics) {
                    Db::name("user_statistics")->where('createDay', date("Y-m-d"))->where('type', 3)->setInc('num', 1);
                } else {
                    Db::name("user_statistics")->insert([
                        'num' => 1,
                        'type' => 3,
                        'createDay' => date("Y-m-d")
                    ]);
                }
            }
            $vip = Db::name("vip")->where('vipId', $vipId)->find();
            if (isset($user['vipTime'])) {
                if (strtotime($user['vipTime']) >= time()) {
                    $vipTime = date("Y-m-d H:i:s", strtotime("+" . $vip['vipDay'] . " Day", strtotime($user['vipTime'])));
                } else {
                    $vipTime = date("Y-m-d H:i:s", strtotime("+" . $vip['vipDay'] . " Day"));
                }
            } else {
                $vipTime = date("Y-m-d H:i:s", strtotime("+" . $vip['vipDay'] . " Day"));
            }
            Db::name("userhome")->where(['id' => $userId])->update(['isVip' => 1, "vipTime" => $vipTime]);
            $vipLog = [];
            $vipLog['userId'] = $userId;
            $vipLog['vipName'] = $vip['vipName'];
            $vipLog['vipPrice'] = $vip['vipPrice'];
            $vipLog['vipDay'] = $vip['vipDay'];
            $vipLog['createTime'] = date("Y-m-d H:i:s");
            $vipLog['endTime'] = $vipTime;
            $vipLog['payType'] = $payType;
            $vipLog['orderNum'] = $oldOrderNum;
            $vipLog['payCode'] = $payCode;
            Db::name("vip_log")->insert($vipLog);
            Db::commit();
        } catch (ValidateException $e) {
            Db::rollback();
            $this->error($e->getMessage());
        } catch (PDOException $e) {
            Db::rollback();
            $this->error($e->getMessage());
        } catch (Exception $e) {
            Db::rollback();
            $this->error($e->getMessage());
        }
    }

//支付宝回调
    public
    function zfb_callback_api_vip()
    {
        //下面三个文件路径一定要改正确
        //支付宝
        include "./aop/AopClient.php";
        include "./aop/AopCertClient.php";
        include "./aop/request/AlipayTradeAppPayRequest.php";
        $root_path = getSystem("root_path");
        $alipayCertPath = $root_path . "public/zhengshu/alipayCertPublicKey_RSA2.crt";//支付宝公钥
        $aop = new \AopClient();
        $c = new \AopCertClient();
        $aop->alipayrsaPublicKey = $c->getPublicKey($alipayCertPath);
        file_put_contents('./success_zfb_cz.txt', var_export($_POST, TRUE));
        $flag = $aop->rsaCheckV1($_POST, NULL, "RSA2");
        DB::name('log')->insert(['content' => json_encode($_POST), 'type' => "ZFBVIP"]);
        if ($_POST['trade_status'] == 'TRADE_SUCCESS') {
            try {
                Db::startTrans();
                $this->setVip($_POST['out_trade_no'], 2, $_POST['trade_no']);
                Db::commit();
                echo 'success';
            } catch (ValidateException $e) {
                Db::rollback();
                $this->error($e->getMessage());
            } catch (PDOException $e) {
                Db::rollback();
                $this->error($e->getMessage());
            } catch (Exception $e) {
                Db::rollback();
                $this->error($e->getMessage());
            }
        } else {
            file_put_contents('./3333.txt', "3333");
            echo 'fail';
        }
    }

//支付回调
    public
    function wx_callback_api_vip()
    {
//        $datas = json_decode('{"appid":"wx4a40935421da4a92","bank_type":"CMB_CREDIT","cash_fee":"1","fee_type":"CNY","is_subscribe":"N","mch_id":"1615039358","nonce_str":"n4dx6g7h84or1q3imuoza3rivfdkhogp","openid":"oj6aC5QS4Kl0oQ4aM4DJMVwT2CSw","out_trade_no":"1658912824U698V1","result_code":"SUCCESS","return_code":"SUCCESS","sign":"3976895FD04121C25700D41CE9445608","time_end":"20220727170714","total_fee":"1","trade_type":"JSAPI","transaction_id":"4200001456202207277719448529"}');
//        $data = [];
//        foreach ($datas as $key => $value) {
//            $data[$key] = $value;
//        }
        $xml = file_get_contents("php://input");
        $data = json_decode(json_encode(simplexml_load_string($xml, 'SimpleXMLElement', LIBXML_NOCDATA)), true);
        DB::name('log')->insert(['content' => json_encode($data), 'type' => "WX"]);
        ksort($data);
        $buff = '';
        foreach ($data as $k => $v) {
            if ($k != 'sign') {
                $buff .= $k . '=' . $v . '&';
            }
        }
        $stringSignTemp = $buff . 'key=7f63d80284392beae6974f43c5c40a59';//key为证书密钥
        $sign = strtoupper(md5($stringSignTemp));
        //判断算出的签名和通知信息的签名是否一致
        if ($sign == $data['sign']) {
            if ($data['result_code'] == "SUCCESS") {
                if ($data['return_code'] == "SUCCESS") {
                    try {
                        Db::startTrans();
                        //业务处理
                        $out_trade_no = $data['out_trade_no'];
                        $this->setVip($out_trade_no, 1, $data['transaction_id']);
                        Db::commit();
                        //处理完成之后，告诉微信成功结果
                        echo exit('<xml><return_code><![CDATA[SUCCESS]]></return_code><return_msg><![CDATA[OK]]></return_msg></xml>');
                    } catch (ValidateException $e) {
                        Db::rollback();
                        $this->error($e->getMessage());
                    } catch (PDOException $e) {
                        Db::rollback();
                        $this->error($e->getMessage());
                    } catch (Exception $e) {
                        Db::rollback();
                        $this->error($e->getMessage());
                    }
                }
            }
        } else {
            echo exit('<xml><return_code><![CDATA[FAIL]]></return_code><return_msg><![CDATA[FAIL]]></return_msg></xml>');
        }
    }

    public function setWelfare($data, $userId,$goods_welfare,$goods,$goodsStock)
    {
        $cutOffTime = strtotime("2022-11-02 23:59:59");
        if($goods['createtime'] <= $cutOffTime){
            $this->error('因疫情原因,当地区已不支持发货', '', 391);
        }
        $address = DB::name('useraddress')->where(['userhome_id' => $userId, 'id' => $data['address_id']])->find();
        if(!$address){
            $this->error("地址已消失");
        }
        $address['address'] = $address['pro_name'] . $address['city_name'] . $address['area_name'] . $address['address'];
        $paycode = date('Ymd') . '1' . substr(implode(NULL, array_map('ord', str_split(substr(uniqid(), 7, 13), 1))), 0, 8) . rand(0, 9);//生成支付单号
        try {
            Db::startTrans();
            $time = time();
            $totalExpressFee = 0;
            $totalGoodsPrice = 0;
            $totalGoodsVipPrice = 0;
            $allPrice = 0;
            $addIntegral = 0;
            $supplier_cost = 0;
            $totalGoodsWelfarePrice = 0;
            $supplier_id = $goods['supplier_id'];
            $expressFee = 0;
            //子单运费
            $expressFee = $this->getFreightRule($address, $goods['expressfee_id'], $goodsStock['zhongliang'], 1, $goods['name']);
            //子单实际支付
            $realityPrice = $goods_welfare['welfare_price'];
            $orderDetail = [];
            $orderDetail['return_mode_id'] = $goods['return_mode_id'];
            $orderDetail['userhome_id'] = $userId;
            $orderDetail['goods_id'] = $goods['id'];
            $orderDetail['goods_spec_one_id'] = $goodsStock['goods_spec_one_id'];
            $orderDetail['goods_spec_two_id'] = $goodsStock['goods_spec_two_id'];
            $orderDetail['image'] = $goods['image'];
            $orderDetail['name'] = $goods['name'];
            if (isset($goodsStock['goods_spec_two_name'])) {
                $orderDetail['goods_spec_name'] = $goodsStock['goods_spec_one_name'] . "/" . $goodsStock['goods_spec_two_name'];
            } else {
                $orderDetail['goods_spec_name'] = $goodsStock['goods_spec_one_name'];
            }
            $orderDetail['num'] = 1;
            $orderDetail['shuilv'] = $goods['shuilv'];
            $orderDetail['cost_price'] = $goodsStock['cost_price'];
            $orderDetail['pure_cost_price'] = $goodsStock['pure_cost_price'];
            $orderDetail['price'] = $goodsStock['price'];
            $orderDetail['vip_price'] = $goodsStock['vip_price'];
            $orderDetail['integral'] = $goodsStock['use_integral'];
            $orderDetail['realityFreight'] = $expressFee;
            $orderDetail['realityPrice'] = $realityPrice;
            $orderDetail['activityStatus'] = 50;
            $orderDetail['welfare_id'] = $goods_welfare['id'];
            $orderDetail['welfare_price'] = $goods_welfare['welfare_price'];
            //计算大订单全部运费
            $totalExpressFee = $totalExpressFee + $expressFee;
            //计算大订单全部商品成本
            $totalGoodsPrice = $totalGoodsPrice + ($goodsStock['price'] * 1);
            //计算大订单全部福利金额
            $totalGoodsWelfarePrice = $totalGoodsWelfarePrice + ($goods_welfare['welfare_price'] * 1);
            //计算vip金额
            $totalGoodsVipPrice = $totalGoodsVipPrice + ($goodsStock['vip_price'] * 1);
            //计算大订单全部实际付款
            $allPrice = $allPrice + $realityPrice + $expressFee;
            $addIntegral = $addIntegral + $goodsStock['use_integral'];
            $supplier_cost = $supplier_cost + ($goodsStock['cost_price'] * 1);
            $order = [
                'supplier_id' => $supplier_id,
                'userhome_id' => $userId,
                'ordernum' => date('Ymd') . '2' . substr(implode(NULL, array_map('ord', str_split(substr(uniqid(), 6, 12), 1))), 0, 8) . rand(0, 9),//生成订单号
                'paycode' => $paycode,
                'orderpaytype' => 1,
                'paytype' => $data['paytype'],
                'price' => $totalGoodsPrice,
                'vip_price' => $totalGoodsVipPrice,
                'freight' => $totalExpressFee,
                'allprice' => $allPrice,
                'phone' => $address['phone'],
                'name' => $address['name'],
                'address' => $address['address'],
                'createtime' => $time,
                'use_integral' => $addIntegral,
                'supplier_cost' => $supplier_cost,
                'isVip' => 0,
                'versions' => 1,
                'activityStatus' => 50,
                'welfare_id' => $goods_welfare['id'],
                'welfare_price' => $totalGoodsWelfarePrice
            ];
            $order_id = DB::name('order')->insertGetId($order);
            //订单详情
            $orderDetail['order_id'] = $order_id;
            $orderDetailId = DB::name('orderdetail')->insertGetId($orderDetail);
            Db::name("goods_welfare")->where('id', $data['welfare_id'])->update([
                'welfare_status'=>1,
                'user_id'=>$userId,
                'order_id'=>$order_id,
                'order_detail_id'=>$orderDetailId,
                'end_time'=>date("Y-m-d H:i:s"),
                'use_time'=>date("Y-m-d H:i:s"),
                'goods_name'=>$orderDetail['name'],
                'goods_stock_image'=>$goodsStock['goods_stock_image'],
                'goods_stock_name'=>$orderDetail['goods_spec_name'],
                'cost_price'=>$orderDetail['cost_price'],
                'pure_cost_price'=>$orderDetail['pure_cost_price']
            ]);
            Db::commit();
        } catch (ValidateException $e) {
            Db::rollback();
            $this->error($e->getMessage());
        } catch (PDOException $e) {
            Db::rollback();
            $this->error($e->getMessage());
        } catch (Exception $e) {
            Db::rollback();
            $this->error($e->getMessage());
        }
        $data = [];
        $data['paycode'] = $paycode;
        $data['order_id'] = $order_id;
        return $data;
    }
}
